package com.cc.visitor.service;

import com.cc.alltype.BusinessException;
import com.cc.visitor.dao.UserWeixinMapper;
import com.cc.visitor.entity.UserWeixin;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

import static com.cc.visitor.entity.table.UserWeixinTableDef.USER_WEIXIN;
/**
 * @author chanchaw
 * @create 2024-09-19 21:32
 */
@Service
public class UserWeixinChecker {
    @Autowired
    private UserWeixinMapper dao;
    public boolean isExists(String openId){
        QueryWrapper queryWrapper = QueryWrapper.create().where(USER_WEIXIN.OPEN_ID.eq(openId));
        UserWeixin userWeixin = dao.selectOneByQuery(queryWrapper);
        return userWeixin == null ? false : true;
    }

    /**
     * 先检测如果已经存在该微信用户则无条件恢复 state = 1并返回 false
     * 相反则返回 true
     * 一般在新增 userWeixin 时调用本方法，返回true则继续新增，相反则退出不新增用户
     * @param openId 微信用户 openId
     * @return false表示接下来不可按照该openId新增用户，相反true表示可新增该用户
     */
    public boolean restore2Valid(String openId){
        QueryWrapper queryWrapper = QueryWrapper.create().where(USER_WEIXIN.OPEN_ID.eq(openId));
        UserWeixin userWeixin = dao.selectOneByQuery(queryWrapper);
        if(userWeixin == null) return true;
        Integer state = Optional.ofNullable(userWeixin.getState()).orElse(0);
        if(state == 1) throw new BusinessException("您已经注册过，无需重复注册！");
        userWeixin.setState(1);
        dao.update(userWeixin);
        throw new BusinessException("已恢复为注册状态！");
    }
}
